package com.duguo.dynamicmvc.view.redirect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.duguo.dynamicmvc.model.Model;

public class RedirectToParentView extends AbstractRedirectView {
	
	private int level=1;
	
    public void render(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {    	
    	if (getViewName() == null) {
	    	initViewName(request);
		}
    	senRedirect(request, response, model,getViewName());
    }

	private void initViewName(HttpServletRequest request) {
		String targetUrl=request.getServletPath();
		if(targetUrl.endsWith("/"))
			targetUrl=targetUrl.substring(0,targetUrl.length()-1);
		int currentLevel=level;
		while(currentLevel>0 && targetUrl.length()>0){
			targetUrl=targetUrl.substring(0,targetUrl.lastIndexOf("/"));
			currentLevel--;
		}
		
		StringBuffer url=new StringBuffer(request.getContextPath());
		url.append(targetUrl);
		url.append("/");
		setViewName(url.toString());
	}
    
	public int getLevel() {
		return level;
	}
	public void setLevel(int level) {
		this.level = level;
	}
    
}
